package com.sport.facilities.booking.system.facebook;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.sport.facilities.booking.db.DatabaseHelper;
import com.sport.facilities.booking.system.AlarmReceiver;
import com.sport.facilities.booking.system.CancelBookingActivity;
import com.sport.facilities.booking.system.FacebookActivity;
import com.sport.facilities.booking.system.R;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.BookingRequestModel;
import com.sport.facilities.booking.system.ui.DialogHelper;
import com.sport.facilities.booking.system.ui.YesAction;

public class MainFragment extends Fragment {

	private static final String TAG = "MainFragment";
	private UiLifecycleHelper uiHelper;
	// private Button publishButton;
	private Button shareButton;
	private Button shareloginButton;
	private static final List<String> PERMISSIONS = Arrays
			.asList("publish_actions");
	private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
	private boolean pendingPublishReauthorization = false;
	private Booking bkdetail;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);

		bkdetail = (Booking) getArguments().getSerializable("bkdetail");

		// MainFragment.newInstance(bkdetail);
		// bkdetail = (Booking) getArguments().getSerializable("bkdetail");
		// Log.e(TAG, "==================" + bkdetail.getBkType());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.facebook, container, false);

		if (bkdetail.getActivity().equalsIgnoreCase("None")) {

			ArrayList<String> myActivities_ArrayList = new ArrayList<String>();

			final List<Booking> myActivities_Obj;

			myActivities_Obj = ActivitiesList();
			
			if(myActivities_Obj.size() == 0){
				//alert empty if Activities is empty
				// alert box success
				//DialogHelper
				//		.getOkAlertDialog(
				//				getActivity(),
				//				"Activities List is Empty",
				//				"No Activities record found.")
				//		.show();
				//Intent intent0 = new Intent(getActivity().getBaseContext(), CancelBookingActivity.class);
				//getActivity().getBaseContext().startActivity(intent0);
				
				
								
								
								YesAction yesAction = new YesAction() {
									public void fnDoYesAction() {

										getActivity().finish();

									}
								};
								
								// alert box share box
								DialogHelper
										.getOkActionDialog(
												getActivity(),
												"Activities List is Empty",
												"No Activities record found.",
												yesAction)
										.show();
											
								
								
			}
			
			Spinner activitiesList = (Spinner) view.findViewById(R.id.spinner1);
			activitiesList.setVisibility(0);

			int count = myActivities_Obj.size();

			for (int i = 0; i < count; i++) {
				myActivities_ArrayList.add(myActivities_Obj.get(i)
						.toDisplayString());
			}

			ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(
					getActivity(), android.R.layout.simple_spinner_item,
					myActivities_ArrayList);
			activitiesList.setAdapter(myAdapter);

			activitiesList
					.setOnItemSelectedListener(new OnItemSelectedListener() {
						@Override
						public void onItemSelected(AdapterView<?> parentView,
								View selectedItemView, int position, long id) {

							String selected = parentView.getItemAtPosition(
									position).toString();

							// Toast.makeText(getActivity(), ""+selected,
							// Toast.LENGTH_LONG).show();

							Booking bkdetail = myActivities_Obj.get(position);

							TextView actType = (TextView) view
									.findViewById(R.id.facebooktv1_1);
							actType.setText(bkdetail.getBkType());
							//actType.setWidth(300);
							//actType.setHeight(80);
							//actType.setPadding(0, 0, 0, 0);
							// Log.e(TAG, bkdetail.getBkType());

							TextView activity = (TextView) view
									.findViewById(R.id.facebooktv3_1);
							activity.setText(bkdetail.getActivity());
							//activity.setWidth(300);
							//activity.setHeight(80);
							//activity.setPadding(0, 0, 0, 0);
							// Log.e(TAG, bkdetail.getActivity());

							TextView court = (TextView) view
									.findViewById(R.id.facebooktv5_1);
							court.setText(bkdetail.getCentre() + " "
									+ bkdetail.getCourt());
							//court.setWidth(300);
							//court.setHeight(80);
							//court.setPadding(0, 0, 0, 0);
							// Log.e(TAG, bkdetail.getCourt());

							TextView date = (TextView) view
									.findViewById(R.id.facebooktv7_1);
							date.setText(bkdetail.getDate());
							//date.setWidth(300);
							//date.setHeight(80);
							//date.setPadding(0, 0, 0, 0);
							// Log.e(TAG, bkdetail.getDate());

							TextView time = (TextView) view
									.findViewById(R.id.facebooktv9_1);
							//time.setText(bkdetail.getTime() + "----"
							//		+ bkdetail.getalarmId());
							time.setText(bkdetail.getTime());
							//time.setWidth(300);
							//time.setHeight(80);
							//time.setPadding(0, 0, 0, 0);

							setBookDetail(bkdetail);

							// fnremovetesttodbandalarm(bkdetail);

							DatabaseHelper db = new DatabaseHelper(
									getActivity());
							// Reading all activity
							Log.d("Reading: ", "Reading all activity..");
							Booking booking = db.getActivitybyDateTime(
									bkdetail.getDate(), bkdetail.getTime());

							String log = "Activity: " + booking.getActivity()
									+ " Type: " + booking.getBkType()
									+ " Centre: " + booking.getCentre()
									+ " Court: " + booking.getCourt()
									+ " Date: " + booking.getDate() + " Time: "
									+ booking.getTime();

							Log.d("--A----A---", log);

						}

						@Override
						public void onNothingSelected(AdapterView<?> parentView) {

						}

					});
			shareButton = (Button) view.findViewById(R.id.shareButton);
			shareButton.setVisibility(8);
			shareButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					

					YesAction yesAction = new YesAction() {
						public void fnDoYesAction() {
							publishStory(bkdetail);
						}
					};
					
					// alert box share box

					DialogHelper.getYesNoDialog(
							getActivity(),
									"Confirm Sharing Booking",
									"Confirm to post this activity on FACEBOOK?",
									yesAction)
							.show();			

					
				}
			});

		} else {

			TextView actType = (TextView) view.findViewById(R.id.facebooktv1_1);
			actType.setText(bkdetail.getBkType());
			//actType.setWidth(300);
			//actType.setPadding(10, 0, 0, 0);
			// Log.e(TAG, bkdetail.getBkType());

			TextView activity = (TextView) view.findViewById(R.id.facebooktv3_1);
			activity.setText(bkdetail.getActivity());
			//activity.setWidth(300);
			//activity.setPadding(10, 0, 0, 0);
			// Log.e(TAG, bkdetail.getActivity());

			TextView court = (TextView) view.findViewById(R.id.facebooktv5_1);
			court.setText(bkdetail.getCentre() + " " + bkdetail.getCourt());
			//court.setWidth(300);
			//court.setPadding(10, 0, 0, 0);
			// Log.e(TAG, bkdetail.getCourt());

			TextView date = (TextView) view.findViewById(R.id.facebooktv7_1);
			date.setText(bkdetail.getDate());
			//date.setWidth(300);
			//date.setPadding(10, 0, 0, 0);
			// Log.e(TAG, bkdetail.getDate());

			TextView time = (TextView) view.findViewById(R.id.facebooktv9_1);
			time.setText(bkdetail.getTime());
			//time.setWidth(300);
			//time.setPadding(10, 0, 0, 0);
			// Log.e(TAG, bkdetail.getTime());

			// TextView actType = (TextView)
			// view.findViewById(R.id.facebooktv2);
			// final String actTypeVal = (String) actType.getText();

			// Log.e(TAG, "-------------" + actTypeVal);
			shareButton = (Button) view.findViewById(R.id.shareButton);
			shareButton.setVisibility(8);
			shareButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//publishStory(bkdetail);
					
					YesAction yesAction = new YesAction() {
						public void fnDoYesAction() {
							publishStory(bkdetail);
						}
					};
					
					// alert box share box

					DialogHelper.getYesNoDialog(
							getActivity(),
									"Confirm Sharing Booking",
									"Confirm to post this activity on FACEBOOK?",
									yesAction)
							.show();	
					
					
				}
			});
		}

		shareloginButton = (Button) view.findViewById(R.id.shareloginButton);
		shareloginButton.setVisibility(0);
		LoginButton authButton = (LoginButton) view
				.findViewById(R.id.authButton);
		authButton.setFragment(this);

		authButton.setReadPermissions(Arrays
				.asList("user_likes", "user_status"));

		if (savedInstanceState != null) {
			pendingPublishReauthorization = savedInstanceState.getBoolean(
					PENDING_PUBLISH_KEY, false);
		}

		return view;
	}

	public ArrayList<Booking> ActivitiesList() {
		 
		ArrayList<Booking> myactivities = new ArrayList<Booking>();

		DatabaseHelper db = new DatabaseHelper(getActivity());
		// Reading all activity
		Log.d("Reading: ", "Reading all activity..");
		List<Booking> booking = db.getAllBooking();

		if (booking.size() != 0) {

			for (Booking cn : booking) {

				myactivities.add(new Booking(cn.getActivity(), cn.getBkType(),
						cn.getCentre(), cn.getCourt(), cn.getDate(), cn
								.getTime(), cn.getalarmId()));

				String log = "Activity: " + cn.getActivity() + " Type: "
						+ cn.getBkType() + " Centre: " + cn.getCentre()
						+ " Court: " + cn.getCourt() + " Date: " + cn.getDate()
						+ " Time: " + cn.getTime();

				// Writing activity to log

				Log.d("---------", log);
			}

		}

		return myactivities;
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (state.isOpened()) {
			// publishButton.setVisibility(View.VISIBLE);

			shareloginButton.setVisibility(8);
			shareButton.setVisibility(0);

			if (pendingPublishReauthorization
					&& state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
				pendingPublishReauthorization = false;
				publishStory(bkdetail);
			}

			Log.i(TAG, "Logged in...");
		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
			// publishButton.setVisibility(View.INVISIBLE);
			shareButton.setVisibility(8);

			shareloginButton.setVisibility(0);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		// uiHelper.onResume();

		Session session = Session.getActiveSession();
		if (session != null && (session.isOpened() || session.isClosed())) {
			onSessionStateChange(session, session.getState(), null);
		}

		uiHelper.onResume();

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {

		super.onSaveInstanceState(outState);
		outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
		uiHelper.onSaveInstanceState(outState);
	}

	/*
	 * public void publishFeedDialog() { Bundle params = new Bundle();
	 * params.putString("name", "Polyu Sports Event");
	 * params.putString("caption", ""); params.putString("description", "");
	 * params.putString("link", ""); params.putString("picture",
	 * "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png"
	 * );
	 * 
	 * WebDialog feedDialog = ( new WebDialog.FeedDialogBuilder(getActivity(),
	 * Session.getActiveSession(), params)) .setOnCompleteListener(new
	 * OnCompleteListener() {
	 * 
	 * @Override public void onComplete(Bundle values, FacebookException error)
	 * { if (error == null) { // When the story is posted, echo the success //
	 * and the post Id. final String postId = values.getString("post_id"); if
	 * (postId != null) { Toast.makeText(getActivity(),
	 * "Posted story, id: "+postId, Toast.LENGTH_SHORT).show(); } else { // User
	 * clicked the Cancel button
	 * Toast.makeText(getActivity().getApplicationContext(),
	 * "Publish cancelled", Toast.LENGTH_SHORT).show(); } } else if (error
	 * instanceof FacebookOperationCanceledException) { // User clicked the "x"
	 * button Toast.makeText(getActivity().getApplicationContext(),
	 * "Publish cancelled", Toast.LENGTH_SHORT).show(); } else { // Generic, ex:
	 * network error Toast.makeText(getActivity().getApplicationContext(),
	 * "Error posting story", Toast.LENGTH_SHORT).show(); } }
	 * 
	 * }) .build(); feedDialog.show(); }
	 */
	public void publishStory(Booking bkdetail) {
		Session session = Session.getActiveSession();

		if (session != null) {

			// Check for publish permissions
			List<String> permissions = session.getPermissions();
			if (!isSubsetOf(PERMISSIONS, permissions)) {
				pendingPublishReauthorization = true;
				Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
						this, PERMISSIONS);
				session.requestNewPublishPermissions(newPermissionsRequest);
				return;
			}

			Bundle postParams = new Bundle();
			postParams.putString("name",
					"Polyu Sport Event: " + bkdetail.getBkType() + " "
							+ bkdetail.getDate());
			postParams.putString("caption",
					"Activity: " + bkdetail.getActivity());
			postParams.putString(
					"description",
					"Event Type: " + bkdetail.getBkType()
							+ "<center></center>Centre: "
							+ bkdetail.getCentre() + " Court: "
							+ bkdetail.getCourt() + "<center></center>Date: "
							+ bkdetail.getDate() + " Time: "
							+ bkdetail.getTime()

			);
			postParams.putString("link", "");
			postParams.putString("picture",
					"http://www.icebergstage.com/polyu.png");

			Request.Callback callback = new Request.Callback() {
				public void onCompleted(Response response) {
					JSONObject graphResponse = response.getGraphObject()
							.getInnerJSONObject();
					String postId = null;
					try {
						postId = graphResponse.getString("id");
					} catch (JSONException e) {
						Log.i(TAG, "JSON error " + e.getMessage());
					}
					FacebookRequestError error = response.getError();
					if (error != null) {
						Toast.makeText(getActivity().getApplicationContext(),
								error.getErrorMessage(), Toast.LENGTH_SHORT)
								.show();
					} else {

						/*
						 * DialogHelper .getOkAlertDialog( getActivity(),
						 * "FACEBOOK Sharing",
						 * "Activity has been successfully posted on FACEBOOK.")
						 * .show();
						 */

						YesAction yesAction = new YesAction() {
							public void fnDoYesAction() {
								//getActivity().finish();
							}
						};

						// alert box share box
						DialogHelper
								.getOkActionDialog(
										getActivity(),
										"FACEBOOK Sharing",
										"Activity has been successfully posted on FACEBOOK.",
										yesAction).show();

						//

						// Toast.makeText(getActivity()
						// .getApplicationContext(),
						// postId,
						// Toast.LENGTH_LONG).show();
					}
				}
			};

			Request request = new Request(session, "me/feed", postParams,
					HttpMethod.POST, callback);

			RequestAsyncTask task = new RequestAsyncTask(request);
			task.execute();
		}

	}

	private boolean isSubsetOf(Collection<String> subset,
			Collection<String> superset) {
		for (String string : subset) {
			if (!superset.contains(string)) {
				return false;
			}
		}
		return true;
	}

	public void setBookDetail(Booking bkdetail) {
		this.bkdetail = bkdetail;
	}

	public static MainFragment newInstance(Booking bkdetail) {
		MainFragment f = new MainFragment();

		// Supply bkdetail input as an argument.
		Bundle args = new Bundle();
		args.putSerializable("bkdetail", bkdetail);
		f.setArguments(args);

		return f;
	}

	public void fnremovetesttodbandalarm(Booking bkdetail) {

		Booking dbbkdetail = new Booking();
		DatabaseHelper db = new DatabaseHelper(getActivity());
		dbbkdetail = db.getActivitybyDateTime(bkdetail.getDate(),
				bkdetail.getTime());
		Intent alarmintent = new Intent(getActivity().getApplicationContext(),
				AlarmReceiver.class);

		AlarmManager am = (AlarmManager) getActivity().getApplicationContext()
				.getSystemService(Context.ALARM_SERVICE);

		Log.d("remove alarm service: ", "" + dbbkdetail.getalarmId());

		PendingIntent sender = PendingIntent.getBroadcast(getActivity()
				.getApplicationContext(), dbbkdetail.getalarmId(), alarmintent,
				PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

		am.cancel(sender);

	}

}
